import { defineStore } from 'pinia'
import { getLangConfig } from '@/api/app'
import i18n from '@/lang'
import cache from '@/utils/cache'
import { LANG_KEY } from '@/enums/cacheEnums'

const { locale } = i18n.global

const cacheLang = cache.get(LANG_KEY)
interface LangSate {
    localLang: string | null
    langList: any
}

export const useLangStore = defineStore({
    id: 'lang',
    state: (): LangSate => {
        return {
            localLang: cacheLang || null,
            langList: [],
        }
    },
    actions: {
        getLangConfig() { 
            return new Promise((resolve, reject) => {
                getLangConfig()
                    .then((data) => {
                        this.langList = data.lang_list
                        if (this.localLang === null) { 
                            this.setLang(data.default_lang)
                        }
                        resolve(data)
                    })
                    .catch((err) => {
                        reject(err)
                    })
            })
        },
        setLang(langValue: string) {
            this.localLang = langValue
            cache.set(LANG_KEY, langValue)
            locale.value = langValue
        }
    }
})

export default useLangStore
